package com.liu.spit.service;

import com.liu.common.utils.IdWorker;
import com.liu.spit.dao.SpitDao;
import com.liu.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SpitService {

    @Autowired
    private SpitDao spitDao;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;


    public List<Spit> findAll(){
        return  spitDao.findAll();
    }


    public Spit findById(String id){
        return  spitDao.findById(id).get();
    }


    public void update(Spit spit){
        spitDao.save(spit);
    }

    public void add(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spitDao.save(spit);
    }

    public void deleteById(String id){
           spitDao.deleteById(id);
    }


    public Page<Spit> findByParentId(String parentid, int page, int size) {


        return  spitDao.findSpitsByParentid(parentid, PageRequest.of(page-1,size));
    }

    public void thumbup(String spitId) {
//  优化代码部分，使用传统的方式，需要先查询一次，然后在将查询的值保存回去，操作两次数据库，
//        使用 mongo 自己的一些特性可以提高效率
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));
        Update update  = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");

    }
}
